package com.baichang.taoshunda.controller;


import com.alipay.util.AlipayNotify;
import com.baichang.framework.controller.BaseController;
import com.baichang.framework.excelption.ServiceException;
import com.baichang.framework.utils.LogUtils;
import com.baichang.taoshunda.weixin.tencent.XMLParser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Dylan on 2017/6/20.
 */
@Controller
@RequestMapping(ControllerConstants.PAY)
public class PayController extends BaseController {


    /**
     * 支付宝回调
     *
     * @param request
     * @param response
     * @return
     * @throws ServiceException
     */
    @RequestMapping("/aliPayNotify")
    public void aliPayNotify(HttpServletRequest request, HttpServletResponse response, PrintWriter out) throws ServiceException {

        // 获取支付宝POST过来反馈信息
        try {
            Map<String, String> params = new HashMap<String, String>();
            Map requestParams = request.getParameterMap();
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                LogUtils.getInstance().info(valueStr);
                params.put(name, valueStr);
            }

            // 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//

            // 商户订单号
            String out_trade_no = null;

            // 支付宝交易号
            String trade_no = null;

            // 交易状态
            String trade_status = null;

            try {
                out_trade_no = new String(request.getParameter("out_trade_no")
                        .getBytes("ISO-8859-1"), "UTF-8");
                trade_no = new String(request.getParameter("trade_no").getBytes(
                        "ISO-8859-1"), "UTF-8");
                trade_status = new String(request.getParameter("trade_status")
                        .getBytes("ISO-8859-1"), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (AlipayNotify.verify(params)) {// 验证成功
                if (trade_status.equals("TRADE_FINISHED")) {
                } else if (trade_status.equals("TRADE_SUCCESS")) {
                }
                // ——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
                out.println("success"); // 请不要修改或删除
            } else {// 验证失败
                out.println("fail");
            }
        } catch (Exception e) {
            LogUtils.getInstance().error(e);
            out.println("fail");
        }
    }

    /**
     * 微信回调
     *
     * @param request
     * @param response
     * @param xml
     * @param writer
     * @throws ServiceException
     */
    @RequestMapping("/weiXinNotify")
    public void success(HttpServletRequest request,
                        HttpServletResponse response, @RequestBody String xml,
                        PrintWriter writer) throws ServiceException {
        response.resetBuffer();
        response.setContentType("text/xml; charset=UTF-8");
        try {
            // 创建请求对象
            Map<String, String> map = XMLParser.xml2map(xml);
            if ("SUCCESS".equals(map.get("return_code"))) {
                String out_trade_no = map.get("out_trade_no");
                String returnXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                writer.print(returnXml);
                writer.flush();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}